package org.meetunexpectedly.controller;

import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.exception.BaseException;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import java.util.StringJoiner;

/**
 * @Description: 异常控制器
 * @Author: pupil
 * @Date: 2024/08/07 下午 5:46
 */
@RestController
@ControllerAdvice
public class ExceptionController {

    /**
     * 处理系统异常信息
     * @param e 系统异常
     * @return 返回异常信息
     */
    @ExceptionHandler(Exception.class)
    public Result ex(Exception e){
        e.printStackTrace();
        String msg = ObjectUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage();
        return Result.error().message(msg);
    }

    /**
     * 处理基础异常
     * @param e 基础异常
     * @return 返回异常信息
     */
    @ExceptionHandler(BaseException.class)
    public Result bex(BaseException e){
        return Result.error().message(e.getMsg());
    }

    /**
     * 请求数据校验异常处理
     * @param e 数据校验异常信息
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result exception(MethodArgumentNotValidException e) {
        // e.getBindingResult()：获取BindingResult  用在实体类校验信息返回结果绑定
        BindingResult bindingResult = e.getBindingResult();
        // 收集数据校验失败后的信息
        StringJoiner joiner = new StringJoiner(",");

        bindingResult.getFieldErrors().stream().forEach((fieldError) -> {
            joiner.add(fieldError.getDefaultMessage());

        });
        return Result.error().message(joiner.toString());
    }
}
